

function c(){
    var x;
    x=new XMLHttpRequest();
    x.onreadystatechange=function() {
        if (x.readyState==4 && x.status==200) {
            console.log(x.responseText);
            var json = JSON.parse(x.responseText);
            json = json.data.reverse();
            for (var i = 0; i < json.length ;i++){
                var li = document.createElement("li");
                var span1 = document.createElement("span");
                span1.className = "col-5";
                span1.innerHTML = json[i].studentName;
                var span2 = document.createElement("span");
                span2.className = "col-4";
                span2.innerHTML = json[i].sex;
                var span3 = document.createElement("span");
                span3.className = "col-3";
                span3.innerHTML = json[i].age;
                li.appendChild(span1);
                li.appendChild(span2);
                li.appendChild(span3);
                document.querySelector("#list").appendChild(li);
            }
        }
    };
    x.open("GET","http://localhost/ajaxApi/public/index.php/index/student/student",true);
    x.send();
}
c();

document.querySelector("#btn").addEventListener('click', function () {
    var n = document.querySelector("#n").value;
    var s = document.querySelector("#s").value;
    var a = document.querySelector("#a").value;
    if (n == "" && a == ""){
        alert("请输入姓名与年龄");
    }else if ( n == ""){
        alert("请输入姓名");
    } else if ( a == "" ){
        alert("请输入年龄");
    } else{
        //ajax执行代码
        var xmlhttp;
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.querySelector("#list").innerHTML = "";
                c();
            }
        };
        xmlhttp.open("GET", "http://localhost/ajaxApi/public/index.php/index/student/addStudent?studentName=" + n + "&sex=" + s + "&age=" + a, true);
        xmlhttp.send();
    }
});